<template>
  <div>
    <MyHeader title="购物车案例"></MyHeader>
    <div class="main">
      <MyGoods
        v-for="item in goodsList"
        :key="item.id"
        :item="item"
        v-model="item.goods_state"
        @changeState="changeStateFn"
        @add="addFn(item.id)"
        @sub="subFn(item.id)"
      ></MyGoods>
    </div>
    <MyFooter :goodsList="goodsList" @changeAll="AllFn"></MyFooter>
  </div>
</template>

<script>
import axios from 'axios'
import MyHeader from './components/MyHeader'
import MyGoods from './components/MyGoods'
import MyFooter from './components/MyFooter'
export default {
  data() {
    return {
      goodsList: [],
    }
  },
  components: {
    MyHeader,
    MyGoods,
    MyFooter,
  },
  methods: {
    changeStateFn(id) {
      this.goodsList.forEach((item) => {
        if (item.id === id) item.goods_state = !item.goods_state
      })
    },
    AllFn(val) {
      this.goodsList.forEach((item) => {
        item.goods_state = val
      })
    },
    addFn(id) {
      // console.log(id)
      this.goodsList.filter((item) => {
        if (item.id === id) item.goods_count++
      })
    },
    subFn(id) {
      this.goodsList.forEach((item) => {
        if (item.id === id && item.goods_count > 0) item.goods_count--
      })
    },
  },
  async created() {
    const { data } = await axios.get('https://www.escook.cn/api/cart')
    console.log(data)
    this.goodsList = data.list
  },
}
</script>
<style>
.main {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
